<template>
  <div>
    <video :id="id" autoplay></video>
  </div>
</template>
<script>
import flv from "flv.js";
export default {
  name: "flv-video",
  components: {},
  props: ["id", "videoUrl"],
  data() {
    return {
      player: null,
      playing: false,
      videoSrc: "",
      loading: false
    };
  },
  created() {},
  watch: {
    videoUrl: {
      handler(newValue) {
        if (flv.isSupported()) {
          if (newValue) {
            this.videoSrc = newValue;
            this.createPlayer(newValue);
          }
        } else {
          this.$message.warning("不支持该播放器");
        }
      }
    }
  },
  methods: {
    createPlayer(videoSrc) {
      this.loading = true;
      this.player = flv.createPlayer({
        type: "flv",
        url: videoSrc,
        isLive: true
      });
      var video = document.getElementById(this.id);
      this.player.attachMediaElement(video);
      try {
        this.loading = false;
        this.player.load();
      } catch (error) {
        console.log(error);
      }
      this.reload();
    },
    // click(){
    //   if(this.playing){
    //     this.player.pause()
    //     this.playing = false;
    //   }
    //   else{
    //     this.player.play()
    //     this.playing = true;
    //   }
    // },
    //关闭播放器
    close() {
      var video = document.getElementById(this.id);
      console.log(video);
      try {
        this.player.pause();
        this.player.unload();
        this.player.detachMediaElement();
        this.player.destroy();
        this.player = null;
      } catch (error) {
        console.log(error);
      }
    },
    //重连
    reload() {
      console.log("监听错误重连");
      this.player.on(flv.Events.ERROR, () => {
        this.loading = true;
        //视频出错后销毁重新创建
        if (this.player) {
          this.player.pause();
          this.player.unload();
          this.player.detachMediaElement();
          this.player.destroy();
          this.player = null;
          this.createPlayer(this.videoUrl);
        }
      });
      // this.player.on(flv.Events.SCRIPTDATA_ARRIVED, function (res) {
      //  console.log('SCRIPTDATA_ARRIVED')
      // });
      // this.player.on(flv.Events.STATISTICS_INFO, function (res) {
      //  console.log('STATISTICS_INFO')
      // });
      // this.player.on(flv.Events.METADATA_ARRIVED, function (res) {
      //  console.log('METADATA_ARRIVED')
      // });
    }
  },
  mounted: function() {},
  computed: {}
};
</script>
<style lang="less" scoped>
video {
  width: 100%;
  height: 100%;
}
</style>
